<?php

namespace App\Services\Order\AfterSale;

use App\Models\AfterSaleOrder;
use App\Models\Order;

class RefundOnly extends PlaceAfterSaleOrder
{
    public function handle($order = null)
    {
        [$totalAmountReturned, $submitSkuIdWithNum] = $this->calculateSubmittedAfterSales($order);

        $afterSaleOrder = AfterSaleOrder::query()->create([
            'agent_id' => \Auth::user()['id'],
            'supplier_id' => $order['commodity_snapshot']['supplier_id'],
            'order_id' => $order['id'],
            'order_numbering' => $order['numbering'],
            'numbering' => $this->makeOrderNumbering('TK'),
            'type' => AfterSaleOrder::TYPE_REFUND_ONLY,
            'refund_amount' => $totalAmountReturned,
            'reason' => $this->request['reason'] ?? '',
            'commodity_id' => $order['commodity_id'],
            'commodity_activity_id' => $order['commodity_activity_id'],
            'client_id' => $order['client_id'],
        ]);

        // 创建售后订单 SKU 数据
        $this->createOrderSku($order, $afterSaleOrder, $submitSkuIdWithNum);
        // 附件 凭证
        $afterSaleOrder->attachments()->sync($this->request['picture_certificate'] ?? []); // 图片
        $temp = [];
        foreach ($this->request['video_certificate'] ?? [] as $attachmentId) {
            $temp[$attachmentId] = ['type' => AfterSaleOrder::ATTACHMENT_TYPE_VIDEO];
        }
        $afterSaleOrder->attachments()->syncWithoutDetaching($temp); // 视频, 这里用 syncWithoutDetaching 不清除上面的图片 ID
    }
}
